package com.chuangjiangx.member.score.web.controller;

import com.chuangjiangx.commons.CurrentThreadContext;
import com.chuangjiangx.commons.page.PagingResult;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.commons.response.UnderlineResponse;
import com.chuangjiangx.member.basic.web.controller.BaseController;
import com.chuangjiangx.member.basic.web.interceptor.Login;
import com.chuangjiangx.member.score.web.request.ScoreInfoListRequest;
import com.chuangjiangx.member.score.web.response.QueryScoreNoticeResponse;
import com.chuangjiangx.member.score.web.response.ScoreDetailResponse;
import com.chuangjiangx.member.score.web.response.ScoreInfoListResponse;
import com.chuangjiangx.member.common.utils.BeanUtils;
import com.chuangjiangx.member.score.ddd.query.MbrScoreNoticeQuery;
import com.chuangjiangx.member.score.ddd.query.MbrScoreStreamQuery;
import com.chuangjiangx.member.score.ddd.dal.condition.QueryMbrScoreStreamCondition;
import com.chuangjiangx.member.score.ddd.dal.dto.MbrScoreStreamList;
import com.chuangjiangx.member.score.ddd.query.dto.AppScoreDetailDTO;
import com.chuangjiangx.member.score.ddd.query.dto.MbrScoreNoticeDTO;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserContext;
import com.chuangjiangx.member.basic.ddd.domain.model.MerchantId;
import com.chuangjiangx.member.score.ddd.domain.model.MbrScoreType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 积分明细
 */
@Slf4j
@RestController
@RequestMapping(value = "/h5/mbr-score-stream", produces = "application/json")
@Api(value = "ScoreInfoController", tags = "积分")
public class ScoreInfoController extends BaseController {


    @Autowired
    private MbrScoreStreamQuery mbrScoreStreamQuery;
    @Autowired
    private MbrScoreNoticeQuery mbrScoreNoticeQuery;


    /**
     * 获取积分明细列表
     *
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     * @map scoreInfoList List
     * @map page
     * @see ScoreInfoListResponse
     */
//    @RequestMapping(value = "/search-score-info-list")
//    @ResponseBody
//    @Login
//    public Response searchScoreInfoList(HttpServletRequest request,
//                                        @Validated  ScoreInfoListRequest scoreInfoListRequest) {
//        MbrUserContext memeberValue = (MbrUserContext) CurrentThreadContext.getCurrentUser();
//
//        //参数转换
//        ScoreStreamForH5Condition condition = new ScoreStreamForH5Condition();
//        BeanUtils.convertBean(scoreInfoListRequest, condition);
//        condition.setEndTime(condition.getEndTime() == null ? null : DateUtils.addDate(condition.getEndTime()));
//
//        condition.setMerchantId(memeberValue.getMerchantId());
//        condition.setMemberId(memeberValue.getMemberId());
//
//        List<ScoreDetailListForH5DTO> list = mbrScoreStreamQuery.getScoreDetailListForH5(condition);
//
//        //对象转换
//        List<ScoreInfoListResponse> respList = new ArrayList<>();
//        list.forEach(scoreDetailListForH5DTO -> {
//            ScoreInfoListResponse response = new ScoreInfoListResponse();
//            response.setCashierDetailDTOList(scoreDetailListForH5DTO.getCashierDetailDTOList());
//            response.setCreateTime(scoreDetailListForH5DTO.getCreateTime());
//            respList.add(response);
//        });
//
//        return ResponseUtils.success("scoreInfoList", respList);
//    }
    @RequestMapping(value = "/search-list", method = RequestMethod.GET)
    @ResponseBody
    @Login
    @ApiIgnore
    public Response searchScoreInfoList(
            @Validated ScoreInfoListRequest request) {
        MbrUserContext user = (MbrUserContext) CurrentThreadContext.getCurrentUser();
        QueryMbrScoreStreamCondition condition = new QueryMbrScoreStreamCondition();
        condition.setMerchantId(user.getMerchantId());
        condition.setMemberId(user.getMemberId());
        condition.setStartTime(request.getStartTime());
        condition.setEndTime(request.getEndTime());

        if (1 == request.getType()) {
            //收入
            condition.setTypes(Arrays.asList(
                    MbrScoreType.CONSUMER.value,
                    MbrScoreType.GIFT.value,
                    MbrScoreType.CARD_GIFT.value
            ));
        } else if (2 == request.getType()) {
            //支出
            condition.setTypes(Arrays.asList(
                    MbrScoreType.REFUND.value,
                    MbrScoreType.EXCHANGE.value
            ));
        }
        //TODO 暂时没有分页
        condition.setPageSize(1000);
        PagingResult<MbrScoreStreamList> pagingResult = mbrScoreStreamQuery.queryMbrScoreStreamList(condition);
        //按天分组
        List<ScoreInfoListResponse> responseList = new ArrayList<>(16);
        if (pagingResult.getTotal() > 0) {
            List<MbrScoreStreamList> items = pagingResult.getItems();
            Map<Date, List<MbrScoreStreamList>> dateListMap = items
                    .stream()
                    .collect(Collectors.groupingBy(
                            o -> DateUtils.truncate(o.getCreateTime(), Calendar.DAY_OF_MONTH)
                    ));
            dateListMap.keySet()
                    .stream()
                    .sorted(Comparator.reverseOrder())
                    .forEach(date -> {
                        ScoreInfoListResponse r = new ScoreInfoListResponse();
                        r.setCreateTime(date);
                        r.setMbrScoreStreamLists(dateListMap.get(date));
                        responseList.add(r);
                    });
        }
        return ResponseUtils.success("scoreInfoList", responseList);
    }

    /**
     * 根据id查询积分明细详情
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    @ResponseBody
    @Login
    @ApiIgnore
    public Response searchScoreInfoById(@PathVariable Long id) {
        ScoreDetailResponse response = new ScoreDetailResponse();
        AppScoreDetailDTO appScoreDetailDTO = mbrScoreStreamQuery.getScoreDetailById(id);
        BeanUtils.convertBean(appScoreDetailDTO, response);
        return ResponseUtils.success(response);
    }

    /**
     * 获取积分须知
     *
     * @return Response
     * @throws Exception
     */
    @ApiOperation(value = "获取积分须知")
    @Login
    @GetMapping(value = "/query-score-notice")
    public UnderlineResponse<QueryScoreNoticeResponse> queryScoreNotice() throws Exception {
        QueryScoreNoticeResponse queryScoreNoticeResponse = new QueryScoreNoticeResponse();
        MbrUserContext user = (MbrUserContext) CurrentThreadContext.getCurrentUser();
        Assert.notNull(user, "登陆用户信息不存在");
        MbrScoreNoticeDTO mbrScoreNoticeDTO = mbrScoreNoticeQuery.queryScoreNotice(new MerchantId(user.getMerchantId()));
        BeanUtils.convertBean(mbrScoreNoticeDTO, queryScoreNoticeResponse);
        return (UnderlineResponse<QueryScoreNoticeResponse>) ResponseUtils.success(queryScoreNoticeResponse);
    }

}
